import { PageContainer } from '@ant-design/pro-components';
import { Select } from 'antd';
import { FC, Suspense, useMemo, useState } from 'react';
import styles from './index.less';
import { dynamicLoadComponent } from './tool';

interface DynamicComponentProps {
  children?: React.ReactNode;
}

// 组件映射，每个对象包含组件的路径和名称
const componentMap = [
  {
    label: '组件1',
    value: 'Product1',
  },
  {
    label: '组件2',
    value: 'Product2',
  },
];

const DynamicComponent: FC = (props: DynamicComponentProps) => {
  console.log({ props });

  const [selectedComponent, setSelectedComponent] = useState(
    componentMap[0].value,
  );

  // 动态导入，并返回组件
  const Component = useMemo(() => {
    return dynamicLoadComponent(selectedComponent);
  }, [selectedComponent]);

  return (
    <PageContainer title="动态导入组件" ghost>
      <div className={styles.dynamic_component_wrap}>
        <h3>
          动态导入组件，减少一次性导入组件引发的全部加载，占用内存过多的问题！！！
        </h3>
        <Select
          style={{ width: 200, marginBottom: 16 }}
          options={componentMap}
          value={selectedComponent}
          onChange={(val) => {
            setSelectedComponent(val);
          }}
        />
        <div>
          <Suspense fallback={<div>Loading...</div>}>
            <Component />
          </Suspense>
        </div>
      </div>
    </PageContainer>
  );
};
export default DynamicComponent;
